#include "stdafx.h"
#include "InputManager.h"
#include "IMouseListener.h"

using namespace std;

namespace ZeEngine
{
    map<string, u32>             InputManager::m_mouseIndexes;
    vector<IMouseListener*>      InputManager::m_sortedMouseListeners;

    Vector2D<s32> InputManager::m_mousePosition;

    InputManager::InputManager()
    {
    }

    InputManager::~InputManager()
    {
    }

    bool InputManager::HandleEvent(SDL_Event& evt)
    {
        bool fHandled = true;

        if (evt.type == SDL_MOUSEMOTION)
        {
            Vector2D<s32> abs(evt.motion.x, evt.motion.y);
            Vector2D<s32> rel(evt.motion.xrel, evt.motion.yrel);

            m_mousePosition = abs;

            for each (auto it in m_sortedMouseListeners)
            {
                auto pListener = it;

                if (pListener)
                {
                    if (pListener->OnMouseMoved(abs, rel))
                    {
                        break;
                    }
                }
            }
        }
        else if (evt.type == SDL_MOUSEBUTTONDOWN)
        {
            Vector2D<s32> abs(evt.motion.x, evt.motion.y);
            for each (auto it in m_sortedMouseListeners)
            {
                auto pListener = it;

                if (pListener)
                {
                    if (pListener->OnMouseButtonPressed(abs, evt.button.button))
                    {
                        break;
                    }
                }
            }
        }
        else if (evt.type == SDL_MOUSEBUTTONUP)
        {
            Vector2D<s32> abs(evt.motion.x, evt.motion.y);
            for each (auto it in m_sortedMouseListeners)
            {
                auto pListener = it;

                if (pListener)
                {
                    if (pListener->OnMouseButtonReleased(abs, evt.button.button))
                    {
                        break;
                    }
                }
            }
        }
        else
        {
            fHandled = false;
        }

        return fHandled;
    }

    void InputManager::AddMouseListener(IMouseListener* pListener, const std::string& name)
    {
        int index = m_sortedMouseListeners.size();
        m_mouseIndexes.insert(pair<string, u32>(name, index));
        m_sortedMouseListeners.push_back(pListener);
    }

    void InputManager::RemoveMouseListener(const std::string& name)
    {
        auto it = m_mouseIndexes.find(name);

        if (it != m_mouseIndexes.end())
        {
            m_sortedMouseListeners[it->second] = NULL;
        }

    }
}
